package com.bestdo.ctrl;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sevenchildren.framework.entity.StringEntry;
import com.sevenchildren.framework.util.NetFileUtils;
import com.sevenchildren.framework.util.http.HttpUtils;

@Controller
@RequestMapping("/test")
public class TestCtrl {
	@RequestMapping("index/{a}/{b}/{c}.html")
	public String index(@PathVariable String a, @PathVariable String b, @PathVariable String c) {
		System.out.println(a + " " + b + " " + c);
		return "index";
	}

	@RequestMapping("download")
	public void download(HttpServletResponse response) throws IOException {
		response.setContentType("application/octet-stream");
		StringEntry<byte[]> se = NetFileUtils.downloadFileByte("http://c.sevenkids.cn/res/img/course/smalldayupdate/u33.jpg");
		response.addHeader("Content-Disposition", "attachment; filename=" + se.code);
		OutputStream outputStream = response.getOutputStream();
		outputStream.write(se.msg);
		outputStream.close();
	}

	@RequestMapping()
	@ResponseBody
	public Object test(HttpServletRequest request, HttpServletResponse response) {
		Enumeration<?> e = request.getHeaderNames();
		Map<String, String> headers = new HashMap<>();
		while (e.hasMoreElements()) {
			String object = (String) e.nextElement();
			headers.put(object.toString(), request.getHeader(object.toString()));
		}

		Map<String, String> params = new HashMap<String, String>();
		Map<?, ?> requestParams = request.getParameterMap();
		for (Iterator<?> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}

		System.out.println(headers);
		System.out.println(params);

		if ("GET".equals(request.getMethod())) {
			return HttpUtils.get("http://c.sevenkids.cn", params, headers).getMsg();
		} else {
			return HttpUtils.post("http://c.sevenkids.cn", null).getMsg();
		}

	}

}
